package com.spider.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.spider.constant.YjsUrl;
import com.spider.entity.YjsPriceEntity;
import com.spider.mapper.HeownsMapper;
import com.spider.util.StringUtil;
import com.spider.util.YjsUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.LinkedHashMap;
import java.util.List;

@Service
public class YjsServiceImpl implements YjsService {

    @Autowired
    RestTemplate restTemplate;
    @Autowired
    HeownsMapper mapper;

    private final Logger logger = LoggerFactory.getLogger(YjsServiceImpl.class);

    /**
     * 价格修改
     * @param  num 默认为空，如果不为空则只跑一次
     */
    @Override
    public void priceUpdate(String num){
        //拼接参数
        String url= YjsUrl.PRODUCT_URL+YjsUrl.PRICE_UPDATE;
        JSONObject apiinfo= YjsUtil.getApiinfo();
        //拼接body
        List<YjsPriceEntity> list = mapper.selectByDate();
        if(list.isEmpty()){
            logger.info("有机所价格推送无数据，推送结束");
        }else{
            logger.info("有机所价格推送查询结果集数量为"+list.size());
            for(YjsPriceEntity entity:list){
                this.sendPriceUpdte(entity,apiinfo,url);
                if(num!=null)break;
            }
        }
    }

    /**
     * 修改有机所价格核心逻辑
     * @param entity
     * @param apiinfo
     * @param url
     */
    private void sendPriceUpdte(YjsPriceEntity entity,JSONObject apiinfo,String url){
        try{
            JSONArray body= YjsUtil.getBody(entity);
            if(body==null){
                logger.info("实体拼接数据失败缺乏数据，跳过此数据:"+entity.toString());
            }
            JSONObject jb=new JSONObject(new LinkedHashMap());
            jb.put("apiinfo",apiinfo);
            jb.put("price",body);
            System.out.println(jb);
            ResponseEntity<String> result=restTemplate.postForEntity(url,jb,String.class);
            String res=StringUtil.unicodeDecode(result.toString());
            System.out.println(res);
/*            ResponseEntity<YjsResult> result=restTemplate.postForEntity(url,jb,YjsResult.class);
            System.out.println(result.getStatusCode());
            System.out.println(result.getStatusCode().equals("200"));
            YjsResult res = result.getBody();
            System.out.println(res.getCode());
            System.out.println(res.getMsg());
            System.out.println(res.getErrors());
            System.out.println(StringUtil.unicodeDecode(result.toString()));*/
            mapper.updateYjsPrice(entity);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("有机所价格推送失败，推送实体是："+entity.toString());
            logger.error("有机所价格推送失败，失败原因："+e.getMessage());
        }
    }

    /**
     * 库存推送
     * @param num 不为空则只推送一条
     */
    @Override
    public void stockUpdate(String num){
        //拼接参数
        String url= YjsUrl.PRODUCT_URL+YjsUrl.STOCK_UPDATE;
        JSONObject apiinfo= YjsUtil.getApiinfo();
        //拼接body
        List<YjsPriceEntity> list = mapper.selectYjsStock();
        if(list.isEmpty()){
            logger.info("有机所库存推送无数据，推送结束");
        }else{
            logger.info("有机所库存推送查询结果集数量为"+list.size());
            for(YjsPriceEntity entity:list){
                try{
                    this.sendStockUpdate(entity,apiinfo,url);
                }catch (Exception e){
                    e.printStackTrace();
                    logger.error("有机所库存推送失败，推送实体是："+entity.toString());
                    logger.error("有机所库存推送失败，失败原因："+e.getMessage());
                }
                if(num!=null)break;
            }
        }
    }

    /**
     * 库存修改核心逻辑
     * @param entity
     * @param apiinfo
     * @param url
     */
    private void sendStockUpdate(YjsPriceEntity entity,JSONObject apiinfo,String url){
        JSONArray body= YjsUtil.getStockBody(entity);
        if(body==null){
            logger.info("实体拼接数据失败缺乏数据，跳过此数据:"+entity.toString());
        }
        JSONObject jb=new JSONObject(new LinkedHashMap());
        jb.put("apiinfo",apiinfo);
        jb.put("stock",body);
        System.out.println(jb);
        ResponseEntity<String> result=restTemplate.postForEntity(url,jb,String.class);
        String res=StringUtil.unicodeDecode(result.toString());
        System.out.println(res);
        mapper.updateYjsStock(entity);
    }
    /**
     * 库存新增
     * @param num 不为空则只推送一条
     */
    @Override
    public void stockInsert(String num){
        //拼接参数
        String url= YjsUrl.PRODUCT_URL+YjsUrl.STOCK_UPDATE;
        JSONObject apiinfo= YjsUtil.getApiinfo();
        //拼接body
        List<YjsPriceEntity> list = mapper.selectYjsInsert();
        if(list.isEmpty()){
            logger.info("有机所新产品库存推送无数据，推送结束");
        }else{
            logger.info("有机所新产品库存推送查询结果集数量为"+list.size());
            for(YjsPriceEntity entity:list){
                try{
                    this.sendStockInsert(entity,apiinfo,url);
                }catch (Exception e){
                    e.printStackTrace();
                    logger.error("有机所新产品库存推送失败，推送实体是："+entity.toString());
                    logger.error("有机所新产品库存推送失败，失败原因："+e.getMessage());
                }
                if(num!=null)break;
            }
        }
    }

    /**
     * 发送插入数据核心逻辑
     * @param entity
     * @param apiinfo
     * @param url
     */
    private void sendStockInsert(YjsPriceEntity entity,JSONObject apiinfo,String url){
        JSONArray body= YjsUtil.getStockBody(entity);
        if(body==null){
            logger.info("实体拼接数据失败缺乏数据，跳过此数据:"+entity.toString());
        }
        JSONObject jb=new JSONObject(new LinkedHashMap());
        jb.put("apiinfo",apiinfo);
        jb.put("stock",body);
        System.out.println(jb);
        ResponseEntity<String> result=restTemplate.postForEntity(url,jb,String.class);
        String res=StringUtil.unicodeDecode(result.toString());
        System.out.println(res);
        //todo 插入log表
        //如果失败则不插入
        //发送后插入有机所数据表-
        mapper.saveYjsInsert(entity);
    }

}
